package jp.sourceforge.akjrcp.text_douga;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

public class BufferedImageFilePathCasher {
private List<String> paths=new ArrayList<String>();
private Map<String,BufferedImage> imageMap=new HashMap<String,BufferedImage>();
private int maxCash=20;//maybe large
		public BufferedImage loadImage(String path){
			BufferedImage img= imageMap.get(path);
			if(img==null){
				try {
					img=ImageIO.read(new File(path));
					imageMap.put(path, img);
					paths.add(path);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				} catch(OutOfMemoryError e2){
					e2.printStackTrace();
					return null;
				}
				
			}else{
				paths.remove(path);
				paths.add(path);//move last
			}
			
			if(paths.size()>=maxCash){
				String removePath=paths.remove(0);
				BufferedImage removeImage=imageMap.remove(removePath);
				//removeImage.
				removeImage.getGraphics().dispose();
				removeImage=null;
			}
			return img;
		}
		public void clear(){
			for(int i=0;i<paths.size();i++){
				BufferedImage removeImage=imageMap.remove(paths.get(i));
				//removeImage.
				removeImage.getGraphics().dispose();
				removeImage=null;
			}
			paths.clear();
			imageMap.clear();
		}
}
